package project2;


import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.util.Date;

public class Util {
	private static Util util;
	private static DateFormat format;
	private static PrintWriter errorOut;
	private static PrintWriter messageOut;
	
	public Util(DateFormat format, PrintWriter errorOut, PrintWriter messageOut) {
		if (util == null) {
			Util.format = format;
			Util.errorOut = errorOut;
			Util.messageOut = messageOut;
		}
	}
	
	// Print Message
	public static void pm(String message) {
		messageOut.println("[SERVER] [" + getTime() + "] " + message);
		messageOut.flush();
	}
	
	// Print main error
	public static void pe(Exception e, String message) {
		errorOut.println("[ERROR] [" + getTime() + "] " + message);
		if (e != null) {
			StackTraceElement[] elem = e.getStackTrace();
			for (int i = 0; i < elem.length; i++) {
				errorOut.println("\t\t" + elem[i].toString());
			}
		}
		errorOut.flush();
	}
	
	// Print specific error from the given socket
	public static void pe(Exception e, String message, Socket soc) {
		String hostName = soc.getInetAddress().getHostName();
		String port = "" + soc.getPort();
		
		errorOut.println("[ERROR] [" + getTime() + "] " + message);
		errorOut.println("[ERROR] From " + hostName + " connected at port " + port + ".");
		if (e != null) {
			StackTraceElement[] elem = e.getStackTrace();
			for (int i = 0; i < elem.length; i++) {
				errorOut.println("\t\t" + elem[i].toString());
			}
		}
		errorOut.flush();
	}
	
	// Print log into the file
	public static void pl(String message) {
		errorOut.println("[SERVER] [" + getTime() + "] " + message);
		errorOut.flush();
	}
	
	private static String getTime() {
		return format.format(new Date());
	}
}
